package org.springblade.task.job.report.book;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.enums.DictBizEnum;
import org.springblade.common.utils.DateUtils;
import org.springblade.modules.booksAnalysis.entity.DailyBookRankingReport;
import org.springblade.modules.booksAnalysis.service.IDailyBookRankingReportService;
import org.springblade.task.base.param.BaseOrderBookParam;
import org.springblade.task.base.param.BaseParam;
import org.springblade.task.base.param.BaseUserClickLogParam;
import org.springblade.task.base.param.BaseUserReadingDataLogParam;
import org.springblade.task.base.service.*;
import org.springblade.task.base.vo.*;
import org.springblade.task.job.base.BaseTaskInfoJob;
import org.springblade.task.quartz.entity.QuartzTask;
import org.springblade.task.quartz.service.IQuartzTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Title: 书籍\分类\出版社\销售 排行
 * @version V1.0
 */
@Component
public class DailyBookRankingReportJob {
	private static Logger logger = LoggerFactory.getLogger(BaseTaskInfoJob.class);

	@Autowired
	private IQuartzTaskService quartzTaskService;
	@Autowired
	private IBaseEbookInfoService baseEbookInfoService;
	@Autowired
	private IBaseUserClickLogService baseUserClickLogService;
	@Autowired
	private IBaseEbookOrderService baseEbookOrderService;
	@Autowired
	private IBaseNetChapterOrderService baseNetChapterOrderService;
	@Autowired
	private IBaseAudioChapterOrderService baseAudioChapterOrderService;
	@Autowired
	private IBaseUserReadingDataLogService baseUserReadingDataLogService;

	@Autowired
	private IDailyBookRankingReportService dailyBookRankingReportService;


	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@XxlJob("dailyBookRankingReportJob")
	public ReturnT<String> dailyBookRankingReportJob(String param) throws Exception {
		System.out.println(DateUtils.currentDateTime() + " -- XXL-JOB, Hello World.");
		System.err.println("执行静态定时任务日期: " + DailyBookRankingReportJob.class.getSimpleName());
		QuartzTask quartzTask = quartzTaskService.queryByTaskName(DailyBookRankingReportJob.class.getSimpleName(), -7);
		// 今日
		String todayDate = DateUtils.crutDate();
		String taskDate = quartzTask.getTaskDate();
		while (taskDate.compareTo(todayDate) < 0) {
			// 当时间大于5点，跳出执行
//			if (DateUtils.getHour24() > 5) {
//				break;
//			}
			// 再加一个凌晨1点判断
			currMethod(taskDate);
			// 增加1天
			taskDate = DateUtils.dateAddDay(taskDate, 1);
		}
		quartzTask.setTaskDate(taskDate);
		quartzTaskService.saveQuartzTask(quartzTask);
		return ReturnT.SUCCESS;
	}

	/**
	 *
	 * @param taskDate
	 */
	public void currMethod(String taskDate) {

		String startTime = DateUtils.getDateStartTime(taskDate);
		String endTime = DateUtils.getDayEndTime(taskDate);
		// 今日之前全部书籍数据
		BaseParam baseParam = new BaseParam();
		baseParam.setToday(endTime);
		List<BaseEbookInfoVO> ebookInfoVOList = baseEbookInfoService.queryEbookList(baseParam);

		// 今日：用户点击日志
		BaseUserClickLogParam logParam = new BaseUserClickLogParam();
		logParam.setStartDate(startTime);
		logParam.setEndDate(endTime);
		logParam.setVFrom(2); // 2或者5 大于0就行
		List<BaseUserClickLogVO> userClickLogVOList = baseUserClickLogService.queryUserClickLogBookList(logParam);

		BaseOrderBookParam orderParam = new BaseOrderBookParam();
		orderParam.setStartDate(startTime);
		orderParam.setEndDate(endTime);
		List<BaseEbookOrderVO> ebookOrderVOList = baseEbookOrderService.queryDailyOrderList(orderParam);
		Map<Long, BaseEbookOrderVO> ebookOrderVOMap = new HashMap<>();
		Map<Long, Long> bookOrderAmountMap = new HashMap<>();
		Map<Long, Integer> bookOrderNumMap = new HashMap<>();
		for (BaseEbookOrderVO orderVO : ebookOrderVOList) {
			ebookOrderVOMap.put(orderVO.getOrderId(), orderVO);
			bookOrderAmountMap.put(orderVO.getEbookId(), bookOrderAmountMap.get(orderVO.getEbookId()) + orderVO.getPayAmount());
			bookOrderNumMap.put(orderVO.getEbookId(), bookOrderNumMap.get(orderVO.getEbookId()) + 1);
		}
		// 网文订单
		List<BaseNetChapterOrderVO> netChapterOrderVOList = baseNetChapterOrderService.queryDailyOrderList(orderParam);
		Map<Long, BaseNetChapterOrderVO> netChapterOrderVOMap = new HashMap<>();
		for (BaseNetChapterOrderVO orderVO : netChapterOrderVOList) {
			netChapterOrderVOMap.put(orderVO.getOrderId(), orderVO);
			bookOrderAmountMap.put(orderVO.getEbookId(), bookOrderAmountMap.get(orderVO.getEbookId()) + orderVO.getOnlineAmount());
			bookOrderNumMap.put(orderVO.getEbookId(), bookOrderNumMap.get(orderVO.getEbookId()) + 1);
		}

		// 有声订单
		List<BaseAudioChapterOrderVO> audioChapterOrderVOList = baseAudioChapterOrderService.queryDailyOrderList(orderParam);
		Map<Long, BaseAudioChapterOrderVO> audioChapterOrderVOMap = new HashMap<>();
		for (BaseAudioChapterOrderVO orderVO : audioChapterOrderVOList) {
			audioChapterOrderVOMap.put(orderVO.getOrderId(), orderVO);
			bookOrderAmountMap.put(orderVO.getEbookId(), bookOrderAmountMap.get(orderVO.getEbookId()) + orderVO.getOnlineAmount());
			bookOrderNumMap.put(orderVO.getEbookId(), bookOrderNumMap.get(orderVO.getEbookId()) + 1);
		}

		// 遍历点击日志
		Map<Long, BaseUserClickLogVO> bookUserClickLogMap = new HashMap<>();
		for (BaseUserClickLogVO logVO : userClickLogVOList) {
			logVO.setEbookId(logVO.getResId());
			if (DictBizEnum.CLICK_TYPE_CLICK_TO_BUY.getValue() == logVO.getClickType()) {
				long amount = 0;
				long ebookId = 0;
				BaseEbookOrderVO ebookOrderVO = ebookOrderVOMap.get(logVO.getResId());
				if (null != ebookOrderVO) {
					amount = ebookOrderVO.getPayAmount();
					ebookId = ebookOrderVO.getEbookId();
				}
				BaseNetChapterOrderVO netChapterOrderVO = netChapterOrderVOMap.get(logVO.getResId());
				if (null != netChapterOrderVO) {
					amount = netChapterOrderVO.getOnlineAmount();
					ebookId = netChapterOrderVO.getEbookId();
				}
				BaseAudioChapterOrderVO audioChapterOrderVO = audioChapterOrderVOMap.get(logVO.getResId());
				if (null != audioChapterOrderVO) {
					amount = audioChapterOrderVO.getOnlineAmount();
					ebookId = audioChapterOrderVO.getEbookId();
				}
				logVO.setAmount(amount);
				logVO.setEbookId(ebookId);
				Set<String> introductionOfPaymentUser = logVO.getIntroductionOfPaymentUser() == null ? new HashSet<>() : logVO.getIntroductionOfPaymentUser();
				introductionOfPaymentUser.add(logVO.getPin());
			}

			// 把用户点击数据放入map中
			BaseUserClickLogVO userClickLogVO = bookUserClickLogMap.get(logVO.getEbookId()) == null ? new BaseUserClickLogVO() : bookUserClickLogMap.get(logVO.getEbookId());
			// 引入阅读次数
			if(DictBizEnum.CLICK_TYPE_READ_NOW.getValue() == logVO.getClickType() ||
				DictBizEnum.CLICK_TYPE_VIP_READING.getValue() == logVO.getClickType()) {
				userClickLogVO.setIntroductionOfReadNum(userClickLogVO.getIntroductionOfReadNum() + 1); // 引入阅读次数
				Set<String> introductionOfReadUser = userClickLogVO.getIntroductionOfReadUser() == null ? new HashSet<>() : userClickLogVO.getIntroductionOfReadUser();
				introductionOfReadUser.add(logVO.getPin());

				userClickLogVO.setIntroductionOfReadUserNum(introductionOfReadUser.size()); // 引入阅读人数
			}
			// 引入加购数量
			else if(DictBizEnum.CLICK_TYPE_ADDITIONAL_PURCHASE.getValue() == logVO.getClickType()) {
				userClickLogVO.setIntroductionOfPurchaseNum(userClickLogVO.getIntroductionOfPurchaseNum() + 1); // 引入加购数量
			}

			// 点击购买
			else if(DictBizEnum.CLICK_TYPE_CLICK_TO_BUY.getValue() == logVO.getClickType()) {
				userClickLogVO.setIntroductionOfPaymentOrderNum(userClickLogVO.getIntroductionOfPaymentOrderNum() + 1); // 引入付费订单量
				userClickLogVO.setIntroductionOfPaymentAmount(userClickLogVO.getIntroductionOfPaymentAmount() + logVO.getAmount()); // 引入付费金额
				userClickLogVO.setIntroductionOfPaymentUserNum(logVO.getIntroductionOfPaymentUser().size()); // 引入付费用户数
			}

			// 点击次数
			userClickLogVO.setClickNum(userClickLogVO.getClickNum() + 1);
			Set<String> clickUser = userClickLogVO.getClickUser() == null ? new HashSet<>() : userClickLogVO.getClickUser();
			clickUser.add(logVO.getPin());

			userClickLogVO.setClickUserNum(clickUser.size()); // 点击人数
		}

		// 查询今日用户阅读数据
		BaseUserReadingDataLogParam readingDataLogParam = new BaseUserReadingDataLogParam();
		readingDataLogParam.setStartDate(DateUtils.getDateStartTime(taskDate));
		readingDataLogParam.setEndDate(DateUtils.getDayEndTime(taskDate));
		List<BaseUserReadingDataLogVO> readingDataLogVOList = baseUserReadingDataLogService.queryTodayReadBookList(readingDataLogParam);
		Map<Long, BaseUserReadingDataLogVO> userReadingDataLogMap = new HashMap<>();
		for (BaseUserReadingDataLogVO vo : readingDataLogVOList) {
			BaseUserReadingDataLogVO readingDataLogVO = userReadingDataLogMap.get(vo.getBookId()) == null ? new BaseUserReadingDataLogVO() : userReadingDataLogMap.get(vo
				.getBookId());
			// 语音朗读
			if (vo.getReadType() == 3) {
				readingDataLogVO.setPlayLength(readingDataLogVO.getPlayLength() + vo.getLength()); // 播放时长
				Set<String> playUser = readingDataLogVO.getPlayUser() == null ? new HashSet<>() : readingDataLogVO.getPlayUser();
				playUser.add(vo.getPin());

				readingDataLogVO.setPlayUserNum(playUser.size()); // 播放人数
			} else {
				readingDataLogVO.setReadLength(readingDataLogVO.getReadLength() + vo.getLength()); // 阅读时长
				Set<String> readUser = readingDataLogVO.getReadUser() == null ? new HashSet<>() : readingDataLogVO.getReadUser();
				readUser.add(vo.getPin());

				readingDataLogVO.setReadUserNum(readUser.size()); // 阅读人数
			}
			readingDataLogVO.setOpenNum(readingDataLogVO.getOpenNum() + 1); // 打开次数
//			readingDataLogVO.setReadFinishUserNum(); // 阅读完成人数
		}
		// 遍历今日全部书籍数据
		List<DailyBookRankingReport> bookRankingReportList = new ArrayList<>();
		DailyBookRankingReport bookRankingReport = null;
		for (BaseEbookInfoVO ebookInfoVO : ebookInfoVOList) {
			bookRankingReport = new DailyBookRankingReport();
			BeanUtils.copyProperties(ebookInfoVO, bookRankingReport);
			long bookId = ebookInfoVO.getEbookId();
			// 书籍订单金额数据
			Long bookOrderAmount = bookOrderAmountMap.get(bookId);
			// 书籍订单数据
			int bookOrderNum = bookOrderNumMap.get(bookId);
			bookRankingReport.setSaleAmount(bookOrderAmount);
			bookRankingReport.setSaleNum(bookOrderNum);

			// 书籍用户点击日志
			BaseUserClickLogVO userClickLogVO = bookUserClickLogMap.get(bookId);
			bookRankingReport.setClickNum(userClickLogVO.getClickNum()); // 点击次数
			bookRankingReport.setClickUserNum(userClickLogVO.getClickUserNum()); // 点击人数
			bookRankingReport.setIntroductionOfReadNum(userClickLogVO.getIntroductionOfReadNum()); // 引入阅读次数
			bookRankingReport.setIntroductionOfReadUserNum(userClickLogVO.getIntroductionOfReadUserNum()); // 引入阅读人数
			bookRankingReport.setIntroductionOfPurchaseNum(userClickLogVO.getIntroductionOfPurchaseNum()); // 引入加购数量
			bookRankingReport.setIntroductionOfPaymentOrderNum(userClickLogVO.getIntroductionOfPaymentOrderNum()); //引入付费订单量
			bookRankingReport.setIntroductionOfPaymentAmount(userClickLogVO.getIntroductionOfPaymentAmount()); // 引入付费金额
			bookRankingReport.setIntroductionOfPaymentUserNum(userClickLogVO.getIntroductionOfPaymentUserNum()); //引入付费用户数
			// 用户阅读数据
			BaseUserReadingDataLogVO userReadingDataLogVO = userReadingDataLogMap.get(bookId);
			bookRankingReport.setReadLength(userReadingDataLogVO.getReadLength()); // 阅读时长
			bookRankingReport.setPlayLength(userReadingDataLogVO.getPlayLength()); // 播放时长
			bookRankingReport.setReadUserNum(userReadingDataLogVO.getReadUserNum()); // 阅读人数
			bookRankingReport.setPlayUserNum(userReadingDataLogVO.getPlayUserNum()); // 播放人数
			bookRankingReport.setOpenNum(userReadingDataLogVO.getOpenNum()); // 打开次数
			bookRankingReport.setReadFinishUserNum(userReadingDataLogVO.getReadFinishUserNum()); // 阅读完成人数

			bookRankingReportList.add(bookRankingReport);
		}

		dailyBookRankingReportService.saveBatch(bookRankingReportList);
	}


	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
